package com.wiwf.model.manage.socket;

import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSONObject;
import com.wiwf.model.bean.SysUserVoto;
import com.wiwf.model.security.service.SysTokenService;

public class BaseWebSocketDispatcher extends TextWebSocketHandler {
	
	private SysTokenService tokenService;
	
	private WebSocketSession session;
	
	public BaseWebSocketDispatcher(SysTokenService tokenService) {
		this.tokenService = tokenService;
	}
	
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
    }
    
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		String strMsg = message.getPayload();
		if(strMsg.indexOf(",")> 0) {
			String[] StrMsgs = strMsg.split(",");
			String key = StrMsgs[0];
			String data = StrMsgs[1];
			
			if(key.equalsIgnoreCase("login")) {
				SysUserVoto sysUser = tokenService.getTokenUser(data);
				if(ObjectUtils.isEmpty(sysUser)) {
					session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"无权限访问\"}"));
				} else {
					setUserInfo(sysUser);
					session.sendMessage(new TextMessage("{\"code\":\"200\", \"data\": "+ JSONObject.toJSONString(sysUser) +"}"));
				}
			} else {
				SysUserVoto sysUser = getUserInfo();
				if(ObjectUtils.isEmpty(sysUser)) {
					session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"无权限访问\"}"));
				} else {
					session.sendMessage(new TextMessage("{\"code\":\"200\", \"msg\": \"ok\"}"));
				}
			}
		} else {
			session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"异常信息\"}"));
		}
	}
	
	private final String userInfoKey = "userInfo";
	
	private void setUserInfo(SysUserVoto sysUser) {
		sysUser.setMenus(null);
		session.getAttributes().put(userInfoKey, sysUser);
	}
	
	private SysUserVoto getUserInfo() {
		return (SysUserVoto) session.getAttributes().get(userInfoKey);
	}
	
	
}
